<?php

namespace Theme;

use W3\Widget;
use W3\Exception;

/**
 * 风格文件列表组件
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Files extends Widget
{
    /**
     * 当前风格
     *
     * @access private
     * @var string
     */
    private $currentTheme;

    /**
     * 当前文件
     *
     * @access private
     * @var string
     */
    private $currentFile;

    /**
     * 执行函数
     *
     * @access public
     * @return void
     */
    public function execute()
    {
        /** 管理员权限 */
        $this->auth->check('admin');
        $this->currentTheme = $this->request->filter('strip_tags')->get('theme', $this->config->theme);

        if (preg_match("/^([_0-9a-z-\.\ ])+$/i", $this->currentTheme)
            && is_dir($dir = $this->themeFile('', $this->currentTheme))) {

            $files = array_filter(glob($dir . '/*'), function ($path) {
                return preg_match("/\.(php|js|css|vbs)$/i", $path);
            });

            $this->currentFile = $this->request->get('file', 'index.php');

            if (preg_match("/^([_0-9a-z-\.\ ])+$/i", $this->currentFile)
            && file_exists($dir . $this->currentFile)) {
                foreach ($files as $file) {
                    if (file_exists($file)) {
                        $file = basename($file);
                        $this->push([
                            'file'      =>  $file,
                            'theme'     =>  $this->currentTheme,
                            'current'   =>  ($file == $this->currentFile)
                        ]);
                    }
                }

                return;
            }
        }
		
		throw new Exception('风格文件不存在', 404);
    }

    /**
     * 获取文件内容
     *
     * @access public
     * @return string
     */
    public function currentContent()
    {
        return htmlspecialchars(file_get_contents($this->themeFile($this->currentFile, $this->currentTheme)));
    }

    /**
     * 获取文件是否可读
     *
     * @access public
     * @return string
     */
    public function currentIsWriteable()
    {
        return is_writeable($this->themeFile($this->currentFile, $this->currentTheme));
    }

    /**
     * 获取当前文件
     *
     * @access public
     * @return string
     */
    public function currentFile()
    {
        return $this->currentFile;
    }

    /**
     * 获取当前风格
     *
     * @access public
     * @return string
     */
    public function currentTheme()
    {
        return $this->currentTheme;
    }
}
